package cn.fuzongyao.learning.android.crime15;


import android.Manifest;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.app.ShareCompat;
import androidx.fragment.app.Fragment;

import java.time.LocalDate;

public class CrimeFragment extends Fragment {
    private static final String ARG_CRIME_ID = "crime_id";
    private static final String DIALOG_DATE = "dialog_date";
    private Crime crime;
    private static final int REQUEST_DATE = 0;
    private static final int REQUEST_CONTACT = 1;
    private Button dateButton;
    private Button suspectButton;
    private static final String TAG = "CriminalIntent";
    private int REQUEST_PERMISSIONS_READ_CONTACTS = 3;
    private Button callButton;


    public static CrimeFragment newInstance(String id) {
        Bundle args = new Bundle();
        args.putSerializable(ARG_CRIME_ID, id);

        CrimeFragment crimeFragment = new CrimeFragment();
        crimeFragment.setArguments(args);
        return crimeFragment;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setHasOptionsMenu(true);

        assert getArguments() != null;
        String id = getArguments().getString(ARG_CRIME_ID);
        crime = CrimeLab.getInstance(getActivity()).getCrime(id);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_crime, container, false);
        EditText titleEditText = view.findViewById(R.id.crime_title);
        titleEditText.setText(crime.getTitle());
        titleEditText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                crime.setTitle(s.toString());
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        });

        dateButton = view.findViewById(R.id.crime_date);
        dateButton.setText(crime.getDate().toString());
        dateButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DatePickerFragment datePickerFragment = DatePickerFragment.newInstance(crime.getDate());
                datePickerFragment.setTargetFragment(CrimeFragment.this, REQUEST_DATE);
                datePickerFragment.show(getFragmentManager(), DIALOG_DATE);
            }
        });

        CheckBox solvedCheckBox = view.findViewById(R.id.crime_solved);
        solvedCheckBox.setChecked(crime.isSolved());
        solvedCheckBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                crime.setSolved(isChecked);
            }
        });

        Button reportButton = view.findViewById(R.id.crime_report);
        reportButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareCompat.IntentBuilder.from(getActivity())
                        .setType("text/plain")
                        .setText(getCrimeReport())
                        .setSubject(getString(R.string.crime_report_subject))
                        .startChooser();
            }
        });

        final Intent pickContact = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
        suspectButton = view.findViewById(R.id.crime_suspect);
        if (crime.getSuspect() != null) {
            suspectButton.setText(crime.getSuspect());
        }
        suspectButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(pickContact, REQUEST_CONTACT);
            }
        });

        callButton = view.findViewById(R.id.crime_call);
        if (crime.getMobile() != null) {
            callButton.setText(callButton.getText() + " " + crime.getMobile());
        }
        callButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (crime.getMobile() != null && !crime.getMobile().isEmpty()) {
                    callSuspect();
                } else {
                    if (!hasReadContacts()) {
                        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.READ_CONTACTS)) {
                            Log.i(TAG, "说明为什么要使用这个权限");
                        } else {
                            Log.i(TAG, "申请权限");
                            String[] permissions = {Manifest.permission.READ_CONTACTS};
                            requestPermissions(permissions, REQUEST_PERMISSIONS_READ_CONTACTS);
                        }
                    } else {
                        callSuspect();
                    }
                }
            }
        });

        ResolveInfo resolveInfo = getActivity().getPackageManager().resolveActivity(pickContact, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo == null) {
            suspectButton.setEnabled(false);
            callButton.setEnabled(false);
        }

        if (crime.getContactId() != null && (crime.getMobile() == null || crime.getMobile().isEmpty()) && hasReadContacts()) {
            updateCallButton();
        }

        final Intent pickCall = new Intent(Intent.ACTION_DIAL);
        resolveInfo = getActivity().getPackageManager().resolveActivity(pickCall, PackageManager.MATCH_DEFAULT_ONLY);
        if (resolveInfo == null) {
            callButton.setEnabled(false);
        }

        return view;
    }

    private boolean hasReadContacts() {
        return getActivity().checkSelfPermission(Manifest.permission.READ_CONTACTS) == PackageManager.PERMISSION_GRANTED;
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.fragment_crime, menu);
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.delete_crime: {
                CrimeLab.getInstance(getActivity()).remove(crime.getId());
                getActivity().finish();
                return true;
            }
            default: {
                return super.onOptionsItemSelected(item);
            }
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == REQUEST_PERMISSIONS_READ_CONTACTS) {
            if (grantResults[0] == PackageManager.PERMISSION_DENIED) {
                Log.d(TAG, "用户没有授权读取联系人");
                return;
            }
            callSuspect();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        if (requestCode == REQUEST_DATE) {
            LocalDate date = (LocalDate) data.getSerializableExtra(DatePickerFragment.EXTRA_DATE);
            crime.setDate(date);
            dateButton.setText(crime.getDate().toString());
        } else if (requestCode == REQUEST_CONTACT && data != null) {
            Uri contactUri = data.getData();
            String[] queryFields = {Contacts._ID, Contacts.DISPLAY_NAME};
            Cursor cursor = getActivity().getContentResolver().query(contactUri, queryFields, null, null, null);
            if (cursor == null || cursor.getCount() < 1) {
                return;
            }

            Integer contactId;
            String suspect;
            try {
                cursor.moveToFirst();
                contactId = cursor.getInt(0);
                suspect = cursor.getString(1);
            } finally {
                cursor.close();
            }

            crime.setContactId(contactId);
            crime.setSuspect(suspect);
            suspectButton.setText(suspect);
            if (hasReadContacts()) {
                updateCallButton();
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        CrimeLab.getInstance(getActivity()).update(crime);
    }

    private String getCrimeReport() {
        String solvedString = null;
        if (crime.isSolved()) {
            solvedString = getString(R.string.crime_report_solved);
        } else {
            solvedString = getString(R.string.crime_report_unsolved);
        }

        String dateString = crime.getDate().toString();
        String suspect = crime.getSuspect();
        if (suspect == null) {
            suspect = getString(R.string.crime_report_no_suspect);
        } else {
            suspect = getString(R.string.crime_report_suspect, suspect);
        }
        String report = getString(R.string.crime_report,
                crime.getTitle(), dateString, solvedString, suspect);
        return report;
    }

    private void callSuspect() {
        if (crime.getMobile() != null && !crime.getMobile().isEmpty()) {
            call(crime.getMobile());
            return;
        }

        //Fetch Phone Number
        updateCallButton();
        call(crime.getMobile());
    }

    private void updateCallButton() {
        String mobile = fetchMobile(crime.getContactId());
        crime.setMobile(mobile);
        callButton.setText(callButton.getText() + " " + crime.getMobile());
    }

    private String fetchMobile(Integer contactId) {
        ContentResolver contentResolver = getActivity().getContentResolver();
        String selection = Phone.CONTACT_ID + " = ?";
        String[] selectionArgs = {contactId + ""};
        Cursor cursor = contentResolver.query(Phone.CONTENT_URI, null, selection, selectionArgs, null);
        if (cursor == null || cursor.getCount() < 1) {
            return null;
        }

        cursor.moveToFirst();
        String mobile = cursor.getString(cursor.getColumnIndex(Phone.NUMBER));
        Log.d(TAG, "id=" + contactId + " phoneNumber=" + mobile);
        cursor.close();
        return mobile;
    }

    private void call(String mobile) {
        Intent pickContact = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + mobile));
        startActivity(pickContact);
    }
}
